<route lang="json5" type="home">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '邻里生活荟',
    navigationStyle: 'default',
  },
}
</route>

<template>
  <view class="page-container min-h-screen pb-8 bg-[#F6F0F0]">
    <view class="sticky top-0 z-10 backdrop-blur-sm bg-white shadow">
      <view class="flex justify-between w-full items-center h-12 box-border px-4">
        <view class="flex-1 flex items-center mr-4">
          <!-- <i class="iconfont icon-zuobiao w-4 h-4 text-orange-500 mr-1"></i> -->
          <image src="http://llcdn.jxsr.com/image/location-pin.png" class="w-4 h-4 mr-0.5" mode="scaleToFill" />

          <text class="text-sm text-gray-700">
            <!-- {{ currentCity }}
            <text class="mx-1 text-gray-300">|</text>
            {{ currentDistrict }}
            <text class="mx-1 text-gray-300">|</text> -->
            {{ currentArea }}
          </text>
        </view>

        <!-- Other Menu Items -->
        <view class="flex-1 flex flex-row justify-end">
          <view class="flex flex-row items-center mr-2 pr-3 border-r-solid border border-r-[#cccccc]">
            <image src="http://llcdn.jxsr.com/person.svg" class="w-5 h-5 mr-1" mode="scaleToFill" />
            <zmxy-number-roller class="f-24 font-medium text-gray-700" :size="12" :number="parseConfigList[0].value" />
          </view>

          <view class="flex flex-row items-center mr-2">
            <image src="http://llcdn.jxsr.com/eye.svg" class="w-5 h-5 mr-1" mode="scaleToFill" />
            <zmxy-number-roller class="f-24 font-medium text-gray-700" :size="12" :number="parseConfigList[1].value" />
          </view>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="w-full justify-center box-border">
      <wd-swiper :list="carouselSlides" autoplay class="w-full" @click="handleSwiperClick" imageMode="widthFix"
        height="422rpx"></wd-swiper>
    </view>

    <!-- 搜索 -->
    <view
      class="rounded-lg overflow-hidden py-2 mx-2 mt-3 flex flex-row justify-between items-center border border-solid border-[#e93b3d] mt-2 bg-white">
      <input class="pl-2 text-xs" v-model="queryStr" placeholder="🔍   输入商品名称" />
      <view class="w-18 text-4 h-7 text-[#e93b3d] leading-7 bl text-center font-bold"
        @click="navigateTo('/pages/product/list?query=' + queryStr)">
        搜索
      </view>
    </view>

    <view class="mx-2 my-3 rounded-xl overflow-hidden bg-white no-scrollbar shadow">
      <view class="font-bold p-2 text-gray-800 bb">便民服务</view>

      <scroll-view v-if="categories.length > 4" class="scroll min-h-14 p-2 no-scrollbar py-2 mt-1" scroll-x="true">
        <view v-for="category in categories" @click="toPage(`/pages/serviceList/index?cateId=${category.id}`)"
          :key="category.id" class="item">
          <view class="w-14 min-h-14 rounded-full shadow flex items-center justify-center mb-1">
            <image :src="category.image" :alt="category.cateName" class="w-8 h-8 object-contain" />
          </view>
          <view class="text-xs w-full text-center text-gray-700">{{ category.cateName }}</view>
        </view>
      </scroll-view>

      <view class="min-h-14 p-2 flex justify-around" v-else>
        <view v-for="category in categories" @click="toPage(`/pages/serviceList/index?cateId=${category.id}`)"
          :key="category.id" class="item-none">
          <view class="w-14 min-h-14 rounded-full shadow flex items-center justify-center mb-1">
            <image :src="category.image" :alt="category.cateName" class="w-8 h-8 object-contain" />
          </view>
          <view class="text-xs w-full text-center text-gray-700">{{ category.cateName }}</view>
        </view>
      </view>
    </view>

    <!-- 探访人气榜 -->
    <view class="flex mx-2 bg-[#FF5A60] p-1 box-content rounded-lg shadow">
      <navigator url="/pages/rank/index" class="text-xs text-shadow" open-type="navigate" hover-class="navigator-hover">
        <view
          class="rounded w-15 h-34 mr-1 p-1 back text-shadow text-shadow-color-black flex flex-col justify-center items-center">
          <image src="http://llcdn.jxsr.com/image/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250418103511.png"
            class="w-10 h-10 mb-3" mode="scaleToFill" />

          <view class="text-xs bg-[#FF5A60] text-white line-clamp-1 px-2 py-0.5 rounded">
            探访榜
          </view>
        </view>
      </navigator>
      <view class="grid grid-cols-3 gap-0.5 flex-1">
        <!-- 列表 -->
        <navigator v-for="item in secCategoryList" :key="item.id" :url="`/pages/rank/index?id=${item.id}`"
          open-type="navigate" hover-class="navigator-hover">
          <view class="rounded h-full bg-white box-border p-1 flex flex-col justify-around items-center">
            <image :src="item.image" class="w-8 h-8" mode="scaleToFill" />
            <view class="text-xs bg-[#FF5A60] text-white line-clamp-1 px-2 py-0.5 rounded">
              {{ item.cateName }}
            </view>
          </view>
        </navigator>
        <!-- 更多 -->
        <navigator url="/pages/rank/index" class="text-xs" open-type="navigate" hover-class="navigator-hover">
          <view
            class="rounded bg-white h-full box-border flex p-1 flex-col justify-around items-center text-shadow text-shadow-color-black">
            <image src="http://llcdn.jxsr.com/image/bangdan.png" class="w-8 h-8" mode="scaleToFill" />
            <view class="text-xs bg-[#FF5A60] text-white line-clamp-1 px-2 py-0.5 rounded">
              更多榜单
            </view>
          </view>
        </navigator>
      </view>
    </view>
    <!-- 产品 -->
    <view class="mx-2 my-3 rounded-xl overflow-hidden bg-white no-scrollbar shadow">
      <view class="mb-2 bb p-2 flex flex-row justify-between items-center">
        <text class="font-bold text-gray-800">热门优惠</text>
        <text class="text-xs text-gray-500" @click="navigateTo('/pages/product/list')">
          查看更多
          <i class="iconfont icon-xiangyou1 w-3 ml-0.5 text-3"></i>
        </text>
      </view>
      <view class="space-y-4 p-2">
        <view v-for="(product, index) in products" :key="product.id" class="flex overflow-hidden pb-2 bb relative"
          @click="toProduct(product)">
          <!-- tag -->
          <wd-tag bg-color="#FE6B6B" custom-class="absolute top-2 right-2" v-if="product?.isSpell == 1">
            优惠
          </wd-tag>
          <wd-tag bg-color="#FFA41B" custom-class="absolute top-2 right-2" v-else>团购</wd-tag>

          <image :src="product.image" :alt="product.name" class="w-28 h-28 rounded-xl object-cover" />
          <view class="flex-1 p-2 flex flex-col justify-between">
            <view class="w-390rpx font-medium text-gray-800 line-clamp-2">{{ product.name }}</view>

            <view class="text-xs text-gray-500 dot pl-2">{{ product.storeName }}</view>

            <view class="text-orange-600 font-bold" v-if="product.isSpell == 1">
              ¥{{ product.vipPrice }}
              <text class="ml-1 text-xs font-normal line-through text-gray-500">
                ¥{{ product.price }}
              </text>
            </view>
            <view class="text-orange-600 font-bold" v-if="product.isSpell == 2">
              ¥{{ product.spellPrice }}
              <text class="ml-1 text-xs font-normal line-through text-gray-500">
                ¥{{ product.price }}
              </text>
            </view>
            <view class="text-xs text-gray-500 pl-1 dot1">已售 {{ product.sales }}</view>
          </view>
        </view>
      </view>
    </view>

    <view class="mx-2 rounded-xl mb-2 overflow-hidden bg-white no-scrollbar shadow" v-if="shenhe == 0">
      <view class="font-bold text-gray-800 bb p-2 mb-2">热门资讯</view>
      <view class="space-y-4 p-2">
        <NewsList :list="newsList" ref="newsListRef" />
      </view>
    </view>

    <wd-loadmore custom-class="loadmore" :state="parseState" />
  </view>
</template>
<script setup>
import { ref } from 'vue'
import { http } from '@/utils/http'
import NewsList from '@/components/NewsList.vue'

const noticeList = ref([])
const products = ref([])
const newsList = ref([])
const categories = ref([])
const configList = ref([])
const carouselSlides = ref([])
const secCategoryList = ref([])

// 添加城市位置相关状态
const amapKey = 'fbacb26edf56429309b33c7ed0e37d0b'
const currentCity = ref('北京')
const currentDistrict = ref('朝阳')
const currentArea = ref('三里屯')

const newsLoading = ref(false)

const queryStr = ref('')

const shenhe = ref(1)

onShareAppMessage(() => {
  return {
    title: '邻里生活荟',
    path: '/pages/index/index',
  }
})
onShareTimeline(() => {
  return {
    title: '邻里生活荟',
    path: '/pages/index/index',
  }
})

const getConfig = async () => {
  let res2 = await http.get('/api/config/list', {
    code: 'shenhe',
  })
  if (res2.code == 200) {
    shenhe.value = Number(res2.data.list[0].value)
  }
}

// 修改getLocation方法，加入行政区域查询
const getLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: async (res) => {
      try {
        // 先获取逆地理编码
        const geoResponse = await uni.request({
          url: `https://restapi.amap.com/v3/geocode/regeo?key=${amapKey}&location=${res.longitude},${res.latitude}`,
        })

        const geoData = geoResponse.data

        if (geoData.status === '1') {
          const { province, city, district } = geoData.regeocode.addressComponent
          currentCity.value = province
          currentDistrict.value = city
          currentArea.value = district
        }
      } catch (error) {
        console.error('获取位置信息失败:', error)
      }
    },
  })
}

const swiperList = ref([])

const navigateTo = (url) => {
  uni.navigateTo({ url })
}

const handleSwiperClick = ({ index }) => {
  if (swiperList.value[index] && swiperList.value[index].url) {
    uni.navigateTo({ url })
  }
}

const parseConfigList = computed(() => {
  return configList.value.slice(0, 2)
})

const intervalTime = ref(15000)

const initData = async () => {
  let res5 = await http.get('/api/config/list')
  if (res5.code == 200) {
    configList.value = res5.data.list

    intervalTime.value =
      configList.value.find((item) => item.code == 'intervalTime')?.value || 15000
  }

  let res = await http.get('/api/home/categories', { type: 1 })

  if (res.code == 200) {
    categories.value = res.data.categories

    categories.value.unshift({
      id: '',
      cateName: '全部',
      image: 'http://llcdn.jxsr.com/917d0304-b766-4c50-9fe2-1ab43d524bb7能.png',
    })
  }

  let resp = await http.get('/api/home/categories', { type: 2, pageNum: 1, pageSize: 5 })

  if (resp.code == 200) {
    secCategoryList.value = resp.data.categories
  }

  let res1 = await http.get('/api/notice/list')
  if (res1.code == 200) {
    noticeList.value = res1.data.list
  }

  let res2 = await http.get('/api/home/products', {
    // isSpell: 1,
    isBest: 1,
    type: 2,
  })
  if (res2.code == 200) {
    products.value = res2.data.products
  }

  let res3 = await http.get('/api/home/banners')
  if (res3.code == 200) {
    carouselSlides.value = res3.data.banners.map((item) => item.image)
    swiperList.value = res3.data.banners
  }

  // let res4 = await http.get('/api/news/list')
  // if (res4.code == 200) {
  //   newsList.value = res4.data.list
  // }

  getNewsList()
}

const toProduct = ({ id, isSpell }) => {
  if (isSpell == 1) {
    uni.navigateTo({ url: `/pages/product/detail?scene=${id}` })
  } else if (isSpell == 2) {
    uni.navigateTo({ url: `/pages/group/product?scene=${id}` })
  }
}

const toPage = (url) => {
  uni.navigateTo({ url })
}

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})

const newsTotal = ref(0)
const nomore = ref(false)

const parseState = computed(() => {
  if (nomore.value) {
    return 'finished'
  } else if (newsLoading.value) {
    return 'loading'
  } else {
    return 'finished'
  }
})

const getNewsList = async () => {
  newsLoading.value = true

  try {
    let res = await http.get('/api/news/list', queryParams.value)
    if (res.code == 200) {
      newsTotal.value = res.data.total
      if (queryParams.value.pageNum == 1) {
        newsList.value = res.data.list
      } else {
        newsList.value = [...newsList.value, ...res.data.list]
      }
    }
  } catch (error) {
    console.log('error', error)
  } finally {
    newsLoading.value = false
  }
}

onReachBottom(() => {
  if (newsList.value.length < newsTotal.value) {
    queryParams.value.pageNum++
    getNewsList()
  } else {
    nomore.value = true
    uni.showToast({ title: '没有更多了', icon: 'none' })
  }
})

onLoad(() => {
  initData()
  getLocation()
  getConfig()
})

const improveNumInterval = ref(null)

const improveNum = async () => {
  // 数字添加
  let res = await http.get('/api/home/modifyConfigData')
  if (res.code == 200) {
    console.log(res)
    configList.value[0].value = res.data.fans
    configList.value[1].value = res.data.views
  }
}

onShow(() => {
  improveNumInterval.value = setInterval(improveNum, intervalTime.value)
})

onHide(() => {
  console.log('onHide')
  clearInterval(improveNumInterval.value)
})

onUnload(() => {
  clearInterval(improveNumInterval.value)
})
</script>

<style scoped>
.swiper {
  width: 686rpx;
}

.scroll {
  width: 686rpx;
  white-space: nowrap;
}

.item {
  display: inline-block;
  width: 112rpx;
  height: auto;
  margin-right: 58rpx;
}

.item-none {
  display: inline-block;
  width: 112rpx;
  height: auto;
}

.back {
  color: #fff;
  background-size: cover;
  box-shadow: #ff6600;
}

.bb {
  border-bottom: 1rpx solid #eee;
}

.bb:last-child {
  border: none;
}

.bg1 {
  background: url(http://llcdn.jxsr.com/0fb700a4-2859-4acf-a64c-1636246c8b4f0.jpg) no-repeat center center;
  background-size: cover;
}

.bg2 {
  background: url(http://llcdn.jxsr.com/0fb700a4-2859-4acf-a64c-1636246c8b4f0.jpg) no-repeat center center;
  background-size: cover;
}

.carousel-container {
  display: flex;
  width: 100%;
  transition: transform 0.5s ease;
}

.carousel-slide {
  min-width: 100%;
}

.announcement-scroll {
  position: relative;
  overflow: hidden;
}

.announcement-scroll view {
  animation: scroll-left 20s linear infinite;
}

@keyframes scroll-left {
  0% {
    transform: translateX(100%);
  }

  100% {
    transform: translateX(-100%);
  }
}

.page-container {
  background-image: url('http://llcdn.jxsr.com/mainback.png') no-repeat;
  background-size: cover;
}

.bl {
  border-left: 1rpx solid #e93b3d;
}

:deep(.wd-swiper__track) {
  border-radius: 0 !important;
}

.dot {
  position: relative;
}

.dot::after {
  position: absolute;
  top: 15rpx;
  left: 0;
  width: 6rpx;
  height: 6rpx;
  content: ' ';

  background-color: #e93b3d;

  border-radius: 50%;
}

.dot1 {
  position: relative;
}

.dot1::after {
  position: absolute;
  top: 15rpx;
  left: 0;
  width: 4rpx;
  height: 4rpx;
  content: ' ';

  background-color: #666;

  border-radius: 50%;
}
</style>
